<?php

//sdeditor上传
function up_sdeditor(){
    $action = isset($_REQUEST['action']) ? $_REQUEST['action'] : '';//这里不能用R('action') 会跟路由里的action冲突
    $allow_action = array('image','music','video','all');     //图片image 音乐music 视频video 所有类型文件all
    if(!in_array($action, $allow_action)){
        echo '{"state":"fail","msg":"错误的参数"}';
        exit();
    }elseif( empty($this->_uid) ){
        echo '{"state":"fail","msg":"未登录不能上传哦"}';
        exit();
    }

    $mid = max(1, (int)R('mid','R'));
    $cid = (int)R('cid','R');
    $id = (int)R('id','R');
    $cfg = $this->runtime->xget();

    if($action == 'image'){
        $allowExt = $cfg['up_img_ext'];
        $maxSize = $cfg['up_img_max_size'];
    }else{
        $allowExt = $cfg['up_file_ext'];
        $maxSize = $cfg['up_file_max_size'];
    }

    if($mid == 1) {
        // 单页上传的图片量小，所以不保存到数据库。
        $updir = $action == 'image' ? 'upload/page/' : 'upload/attach/page/';
        $config = array(
            'maxSize'=>$maxSize,
            'allowExt'=>$allowExt,
            'upDir'=>ROOT_PATH.$updir,
        );
        $up = new upload($config, 'upfile');
        $info = $up->getFileInfo();
    }else{
        // 非单页模型
        $table = $this->models->get_table($mid);
        $updir = $action == 'image' ? 'upload/'.$table.'/' : 'upload/attach/'.$table.'/';
        $config = array(
            'maxSize'=>$maxSize,
            'allowExt'=>$allowExt,
            'upDir'=>ROOT_PATH.$updir,
        );

        if( isset($_GET['nodb']) ){ //不写入附件表
            $up = new upload($config, 'upfile');
            $info = $up->getFileInfo();
        }else{
            $this->cms_content_attach->table = 'cms_'.$table.'_attach';
            $info = $this->cms_content_attach->uploads($config, $this->_user['uid'], $cid, $id);
        }
    }

    $path = $updir.$info['path'];

    if($info['state'] == 'SUCCESS') {
        if($action == 'image' && !empty($cfg['watermark_pos'])){    //图片加水印
            image::watermark(ROOT_PATH.$path, ROOT_PATH.'static/img/watermark.png', null, $cfg['watermark_pos'], $cfg['watermark_pct']);
        }
        echo '{"state":"success","msg":"'.$cfg['weburl'].$path.'","name":"'.$info['name'].'"}';
    }else{
        echo '{"state":"fail","msg":"'.$info['state'].'"}';
    }
    exit();
}
